package com.xxl.job.executor.jobhandler;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.jobhandler.impl.EveryDayExecute;
import com.xxl.job.sscIntegrInfo.domain.SscIntegrInfoVo;
import com.xxl.job.sscIntegrInfo.service.ISscIntegrInfoService;
import com.xxl.job.sscMemberSysmessage.domain.SscMemberSysmessage;
import com.xxl.job.sscMemberSysmessage.service.ISscMemberSysmessageService;
import com.xxl.job.sysStoreUserMessagePush.domain.SysStoreUserMessagePush;
import com.xxl.job.sysStoreUserMessagePush.service.ISysStoreUserMessagePushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;

/**
 * 任务积分 Job
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author zyc
 * @version : 1.0
 * @create : 2023/08/29 16:05
 */
@Component
public class TimedTaskJobHandler {

    private static final Logger log = LoggerFactory.getLogger(TimedTaskJobHandler.class);

    @Autowired
    private List<EveryDayExecute> everyDayExecutes;

    @Autowired
    private ISscIntegrInfoService iSscIntegrInfoService;

    @Autowired
    private ISscMemberSysmessageService iSscMemberSysmessageService;

    @Autowired
    private ISysStoreUserMessagePushService iSysStoreUserMessagePushService;

    /**
     * 积分 - 每日任务
     *
     * @author: zyc
     * @date: 2023/9/1 11:43
     */
    @XxlJob("everyDayExecuteJobHandle")
    public ReturnT<String> everyDayExecuteJobHandle() {
        if (everyDayExecutes == null || everyDayExecutes.size() == 0) {
            return ReturnT.SUCCESS;
        }

        for (EveryDayExecute dayExecute : everyDayExecutes) {
            try {
                dayExecute.execute();
            } catch (Exception e) {
                log.error("每日任务异常" + e);
            }
        }
        return ReturnT.SUCCESS;
    }


    /**
     * 任务积分未领取已失效, 定时更新 [积分状态为已失效]
     *
     * @author: zyc
     * @date: 2023/8/30 10:43
     */
    @Transactional(rollbackFor = Exception.class)
    @XxlJob("inlLoseEfficacy")
    public ReturnT<String> inlLoseEfficacy() {
        try {
            log.info("-- 开始更新失效积分数据");
            int count = iSscIntegrInfoService.updateInlLoseEfficacy();
            log.info("-- 已更新失效积分 [" + count + "] 条");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新失效积分数据出现异常 : " + e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 任务积分临期提醒
     *
     * @author: zyc
     * @date: 2023/8/30 10:43
     */
    @Transactional(rollbackFor = Exception.class)
    @XxlJob("inlAdventRemind")
    public ReturnT<String> inlAdventRemind() {
        try {
            // 临期天数
            Integer adventDay = 3;

            SscIntegrInfoVo infoVo = new SscIntegrInfoVo();
            infoVo.setAdventDay(adventDay);
            List<SscIntegrInfoVo> list = iSscIntegrInfoService.selectIntegralAdventList(infoVo);
            for (SscIntegrInfoVo fIntegral : list) {
                // 数据封装
                HashMap<String, Object> pcMaps = new HashMap<>();
                pcMaps.put("businessDescribe", "用户临期积分提醒");
                pcMaps.put("businessType", "adventIntegral");
                pcMaps.put("memberId", fIntegral.getMemberId());
                pcMaps.put("adventDay", adventDay);
                pcMaps.put("closeDate", fIntegral.getCloseDate());
                pcMaps.put("advTotalIntegral", fIntegral.getAdvTotalIntegral());

                // 新增消息推送
                SysStoreUserMessagePush iMsgPush = new SysStoreUserMessagePush();
                iMsgPush.setMsgType("3");
                iMsgPush.setIsOfficial("11");
                iMsgPush.setPushContent(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(pcMaps))));
                iMsgPush.setCreateBy("admin");
                iSysStoreUserMessagePushService.insertSysStoreUserMessagePush(iMsgPush);

                // 新增会员接收消息推送
                SscMemberSysmessage iMemberSys = new SscMemberSysmessage();
                iMemberSys.setSysPushId(iMsgPush.getSysPushId());
                iMemberSys.setReceiveMemberId(fIntegral.getMemberId());
                iMemberSys.setCreateBy("admin");
                iSscMemberSysmessageService.insertSscMemberSysMessage(iMemberSys);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理任务积分临期提醒出现异常 : " + e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ReturnT.SUCCESS;
    }
}
